package services

import (
	"errors"
	"lingc/models"
	"lingc/utils"
	"time"

	"gorm.io/gorm"
)

// AuthRuleService 提供账号登录校验的服务
type AuthRuleService struct {
	DB *gorm.DB
}

// NewAuthRuleService 创建一个新的 AuthRuleService 实例
func NewAuthRuleService(db *gorm.DB) *AuthRuleService {
	return &AuthRuleService{DB: db}
}

//表单业务

/**
 * @Description: 分页获取权限组列表
 * @param where
 * @param page
 * @param pageSize
 * @return []*models.AuthRule
 * @return int
 * @return int64
 * @return error
 */
func (s *AuthRuleService) PageAuthRuleList(where string) ([]*models.AuthRuleList, []*models.AuthRuleOptions, int64, error) {
	var rules []*models.AuthRule
	var total int64
	// 获取总记录数
	if err := s.DB.Model(&models.AuthRule{}).Where(where).Count(&total).Error; err != nil {
		return nil, nil, 0, err
	}

	// 获取分页数据
	if err := s.DB.Where(where).Find(&rules).Error; err != nil {
		return nil, nil, 0, err
	}
	var list []*models.AuthRuleList
	list = []*models.AuthRuleList{}
	var options []*models.AuthRuleOptions
	options = []*models.AuthRuleOptions{}
	for _, rule := range rules {
		list = append(list, &models.AuthRuleList{
			ID:        rule.ID,
			Name:      rule.Name,
			Title:     rule.Title,
			URL:       rule.URL,
			URLParam:  rule.URLParam,
			Icon:      rule.Icon,
			Type:      rule.Type,
			APIMethod: rule.APIMethod,
			Rank:      rule.Rank,
			ParentID:  rule.ParentID,
			AppID:     rule.AppID,
			Status:    rule.Status,
			CreatedAt: time.Unix(rule.CreatedAt, 0).Format("2006-01-02 15:04:05"),
			UpdatedAt: time.Unix(rule.UpdatedAt, 0).Format("2006-01-02 15:04:05"),
		})
		options = append(options, &models.AuthRuleOptions{
			Value:    rule.ID,
			Label:    rule.Title,
			ParentID: rule.ParentID,
			Children: []*models.AuthRuleOptions{},
		})
	}
	list = utils.ArrayToTreeList(list)
	options = utils.ArrayToTreeOptions(options)
	return list, options, total, nil
}

// 获取分页数据
func (s *AuthRuleService) PageAuthRuleIds(idstr string) (string, error) {
	var rules []*models.AuthRule
	// 将 idstr 转换为数组
	ids := utils.StringToUintSlice(idstr) // 修改：将字符串转换为数组
	// 获取分页数据
	if err := s.DB.Where("id IN ?", ids).Find(&rules).Error; err != nil {
		return "", err
	}
	rule_ids := []uint{}
	var options []*models.AuthRuleOptions
	options = []*models.AuthRuleOptions{}
	for _, rule := range rules {
		options = append(options, &models.AuthRuleOptions{
			Value:    rule.ID,
			Label:    rule.Title,
			ParentID: rule.ParentID,
			Children: []*models.AuthRuleOptions{},
		})
	}
	// options = utils.ArrayToTreeOptions(options)
	rule_ids = utils.ArrayToTreeChildrenId(options)
	// 将数组转换为逗号分隔的字符串
	rule_ids_str := ""
	if len(rule_ids) > 0 {
		rule_ids_str = utils.UintSliceToString(rule_ids, ",")
	}
	return rule_ids_str, nil
}

/**
 * @Description: 创建新权限组
 * @return *models.AuthRuleCreate
 * @return error
 */
func (s *AuthRuleService) CreateAuthRule(rule *models.AuthRuleCreate) (*models.AuthRuleCreate, error) {
	// 检查权限组名是否已存在
	var existingUser models.AuthRule
	if err := s.DB.Where("name = ?", rule.Name).First(&existingUser).Error; err == nil {
		return nil, errors.New("权限组名已存在")
	}
	/*
		Name      string `json:"name"`
		Title     string `json:"title"`
		URL       string `json:"url"`
		URLParam  string `json:"url_param"`
		Icon      string `json:"icon"`
		Type      uint8  `json:"type"`
		APIMethod uint8  `json:"api_method"`
		Rank      uint   `json:"rank"`
		ParentID  uint   `json:"parent_id"`
		AppID     int    `json:"app_id"`
		Status    uint8  `json:"status"`
	*/
	addData := &models.AuthRule{
		Name:      rule.Name,
		Title:     rule.Title,
		URL:       rule.URL,
		URLParam:  rule.URLParam,
		Icon:      rule.Icon,
		Type:      rule.Type,
		APIMethod: rule.APIMethod,
		Rank:      rule.Rank,
		ParentID:  rule.ParentID,
		Status:    rule.Status,
		CreatedAt: time.Now().Unix(),
		UpdatedAt: time.Now().Unix(),
	}
	// 保存新权限组到数据库
	if err := s.DB.Create(addData).Error; err != nil {
		return nil, err
	}
	return rule, nil
}

// GetAuthRule 获取权限组信息
func (s *AuthRuleService) GetAuthRule(where string) (*models.AuthRule, error) {
	var data models.AuthRule
	if err := s.DB.Where(where).First(&data).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("权限组不存在")
		}
		return nil, err
	}
	// log.Printf("data_info:%v", data.AuthRuleAccess)
	return &data, nil
}

/**
 * @Description: 更新权限组信息
 * @param data
 * @return error
 */
func (s *AuthRuleService) UpdateAuthRule(rule *models.AuthRuleUpdate) (*models.AuthRuleUpdate, error) {
	// 检查权限组名是否已存在
	var existingUser models.AuthRule
	if err := s.DB.Where("id = ?", rule.ID).First(&existingUser).Error; err != nil {
		return nil, errors.New("数据不存在")
	}
	existingUser.Title = rule.Title
	existingUser.Name = rule.Name
	existingUser.URL = rule.URL
	existingUser.URLParam = rule.URLParam
	existingUser.Icon = rule.Icon
	existingUser.Type = rule.Type
	existingUser.APIMethod = rule.APIMethod
	existingUser.Rank = rule.Rank
	existingUser.ParentID = rule.ParentID
	existingUser.Status = rule.Status

	return rule, s.DB.Save(existingUser).Error
}

/**
 * @Description: 删除权限组
 * @param id
 * @return error
 */
func (s *AuthRuleService) DeleteAuthRule(id uint) error {
	var rule models.AuthRule
	if err := s.DB.Where("id = ?", id).First(&rule).Error; err != nil {
		return errors.New("数据不存在")
	}
	return s.DB.Delete(&rule).Error
}

/**
 * @Description: 批量删除权限组
 * @param id
 * @return error
 */
func (s *AuthRuleService) DeleteAuthRules(ids []string) error {
	var rule models.AuthRule
	if err := s.DB.Where("id IN ?", ids).Delete(&rule).Error; err != nil {
		return errors.New("删除失败")
	}
	return nil
}
